package com.example.sherlockzhong.plush_v2.Subscriptions;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.Components.buttons.BackButton;
import com.example.sherlockzhong.plush_v2.Components.buttons.VoiceButton;
import com.example.sherlockzhong.plush_v2.Models.TodoModel;
import com.example.sherlockzhong.plush_v2.R;
import com.example.sherlockzhong.plush_v2.Utils.DateTimeUtil;
import com.example.sherlockzhong.plush_v2.Utils.StorageUtils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class TodoActivity extends Activity {

    private TodoActivity self = this;

    private LinearLayout todoListLayout;

    private LinearLayout textBtn;
    private LinearLayout voiceBtn;

    private ScrollView textWindow;
    private ScrollView voiceWindow;

    private DatePicker textDatePicker;
    private TimePicker textTimePicker;
    private DatePicker voiceDatePicker;
    private TimePicker voiceTimePicker;

    private TextView textTime;
    private EditText textContent;
    private Button textSave;
    private Button textCancel;
    private TextView textHint;

    private TextView voiceLength;
    private TextView voiceTime;
    private Button voiceSave;
    private Button voiceCancel;
    private ImageButton voiceRecord;
    private String currentVoicePath = null;

    private ImageView press;
    private ImageView release;

    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private String setDateTime;

    private Timer voiceRecordTimer;
    private TimerTask voiceRecordTimerTask;
    private int voiceLengthMax = 60;
    private Handler voiceRecordHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                voiceLength.setText("录音中：" + voiceLengthMax + "s");
            } else if (msg.what == 0) {
                stopRecording();
            }
            super.handleMessage(msg);
        }
    };
    private int voiceLengthRecorded = 0;

    private MediaPlayer voicePlayer;
    private MediaRecorder voiceRecorder;
    private boolean voiceIsPlaying = false;
    private boolean voiceIsRecording = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_todo);

        BackButton todo_back = (BackButton) findViewById(R.id.todo_back);
        todo_back.setApp(this);

        initWidgets();
        loadTodoList();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    private void initWidgets() {
        //获取屏幕宽
        Display display = getWindowManager().getDefaultDisplay();
        Point p = new Point();
        display.getSize(p);
        final int windowWidth = p.x;

        todoListLayout = (LinearLayout) findViewById(R.id.todo_list);

        textBtn = (LinearLayout) findViewById(R.id.todo_text_btn);
        voiceBtn = (LinearLayout) findViewById(R.id.todo_voice_btn);

        textWindow = (ScrollView) findViewById(R.id.todo_text_window);
        voiceWindow = (ScrollView) findViewById(R.id.todo_voice_window);

        textTime = (TextView) findViewById(R.id.todo_text_time);
        textContent = (EditText) findViewById(R.id.todo_text_content);
        textSave = (Button) findViewById(R.id.todo_text_save);
        textCancel = (Button) findViewById(R.id.todo_text_cancel);
        textHint = (TextView) findViewById(R.id.todo_text_hint);

        press = (ImageView)findViewById(R.id.voice_press);
        release = (ImageView)findViewById(R.id.voice_release);
        press.setVisibility(View.GONE);
        release.setVisibility(View.VISIBLE);

        voiceLength = (TextView) findViewById(R.id.todo_voice_length);
        voiceTime = (TextView) findViewById(R.id.todo_voice_time);
        voiceSave = (Button) findViewById(R.id.todo_voice_save);
        voiceCancel = (Button) findViewById(R.id.todo_voice_cancel);
        voiceRecord = (ImageButton) findViewById(R.id.todo_voice_record);

        textDatePicker = (DatePicker) findViewById(R.id.text_date_picker);
        textTimePicker = (TimePicker) findViewById(R.id.text_time_picker);
        voiceDatePicker = (DatePicker) findViewById(R.id.voice_date_picker);
        voiceTimePicker = (TimePicker) findViewById(R.id.voice_time_picker);

        //设置pickers大小
        LinearLayout textdpContainer = (LinearLayout)textDatePicker.getChildAt(0);
        LinearLayout textdpSpinner = (LinearLayout)textdpContainer.getChildAt(0);
        LinearLayout texttpContainer = (LinearLayout)textTimePicker.getChildAt(0);
        LinearLayout texttpSpinner = (LinearLayout)texttpContainer.getChildAt(0);

        int spinnerWidth =  windowWidth/8;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(spinnerWidth,ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(16,16,0,0);

        for(int i = 0;i<textdpSpinner.getChildCount();i++){
            NumberPicker numberPicker = (NumberPicker)textdpSpinner.getChildAt(i);
            numberPicker.setLayoutParams(params);
        }
        for(int i = 0;i<texttpSpinner.getChildCount();i++){
            Object o = texttpSpinner.getChildAt(i);
            if(o instanceof NumberPicker) {
                NumberPicker numberPicker = (NumberPicker) texttpSpinner.getChildAt(i);
                numberPicker.setLayoutParams(params);
            }
        }

        //设置pickers大小
        LinearLayout voicedpContainer = (LinearLayout)voiceDatePicker.getChildAt(0);
        LinearLayout voicedpSpinner = (LinearLayout)voicedpContainer.getChildAt(0);
        LinearLayout voicetpContainer = (LinearLayout)voiceTimePicker.getChildAt(0);
        LinearLayout voicetpSpinner = (LinearLayout)voicetpContainer.getChildAt(0);
        for(int i = 0;i<voicedpSpinner.getChildCount();i++){
            NumberPicker numberPicker = (NumberPicker)voicedpSpinner.getChildAt(i);
            numberPicker.setLayoutParams(params);
        }
        for(int i = 0;i<voicetpSpinner.getChildCount();i++){
            Object o = voicetpSpinner.getChildAt(i);
            if(o instanceof NumberPicker){
                NumberPicker numberPicker = (NumberPicker)voicetpSpinner.getChildAt(i);
                numberPicker.setLayoutParams(params);
            }
        }

        //获取当前的年、月、日、小时、分钟
        String currentDateTime = DateTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm");
        String currentDate = currentDateTime.split(" ")[0];
        String currentTime = currentDateTime.split(" ")[1];
        String[] currentDateParts = currentDate.split("-");
        String[] currentTimeParts = currentTime.split(":");
        year = Integer.parseInt(currentDateParts[0]);
        month = Integer.parseInt(currentDateParts[1]);
        day = Integer.parseInt(currentDateParts[2]);
        hour = Integer.parseInt(currentTimeParts[0]);
        minute = Integer.parseInt(currentTimeParts[1]);
        showTextDate(year, month, day, hour, minute);
        showVoiceDate(year, month, day, hour, minute);

        textDatePicker.init(year, month - 1, day, new OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker arg0, int year
                    , int month, int day) {
                TodoActivity.this.year = year;
                TodoActivity.this.month = month + 1;
                TodoActivity.this.day = day;
                //显示当前日期、时间
                showTextDate(TodoActivity.this.year, TodoActivity.this.month, TodoActivity.this.day, hour, minute);
            }
        });
        //为TimePicker指定监听器
        textTimePicker.setIs24HourView(true);
        textTimePicker.setCurrentHour(hour);
        textTimePicker.setCurrentMinute(minute);
        textTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker arg0, int hour, int minute) {
                TodoActivity.this.hour = hour;
                TodoActivity.this.minute = minute;
                //显示当前日期、时间
                showTextDate(year, month, day, TodoActivity.this.hour, TodoActivity.this.minute);
            }
        });

        voiceDatePicker.init(year, month - 1, day, new OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker arg0, int year
                    , int month, int day) {
                TodoActivity.this.year = year;
                TodoActivity.this.month = month + 1;
                TodoActivity.this.day = day;
                //显示当前日期、时间
                showVoiceDate(TodoActivity.this.year, TodoActivity.this.month, TodoActivity.this.day, hour, minute);
            }
        });
        //为TimePicker指定监听器
        voiceTimePicker.setIs24HourView(true);
        voiceTimePicker.setCurrentHour(hour);
        voiceTimePicker.setCurrentMinute(minute);
        voiceTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker arg0, int hour, int minute) {
                TodoActivity.this.hour = hour;
                TodoActivity.this.minute = minute;
                //显示当前日期、时间
                showVoiceDate(year, month, day, TodoActivity.this.hour, TodoActivity.this.minute);
            }
        });

        textBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                voiceWindow.setVisibility(View.GONE);
                textWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_in);
                textWindow.startAnimation(animation);
            }
        });

        textSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveTodoText();
            }
        });

        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_out);
                textWindow.startAnimation(animation);
                textWindow.setVisibility(View.GONE);
            }
        });

        voiceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textWindow.setVisibility(View.GONE);
                voiceWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_in);
                voiceWindow.startAnimation(animation);
            }


        });


        voiceRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                voiceRecordMotionEventHandler(motionEvent);
                return true;
            }
        });

        voiceSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveTodoVoice();
            }
        });

        voiceCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                voiceWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_out);
                voiceWindow.startAnimation(animation);
                voiceWindow.setVisibility(View.GONE);
                stopRecording();
                voiceRecord.setImageResource(R.drawable.microphone);
                voiceLength.setText("可录音：" + voiceLengthMax + "s");
                voiceLengthRecorded = 0;
            }
        });

        textContent.addTextChangedListener(new EditChangeListener());
    }

    private void showTextDate(int year, int month, int day, int hour, int minute) {
        String Month;
        String Date;
        String Hour;
        String Minute;
        Month = month < 10 ? ("0" + (new Integer(month)).toString()) : (new Integer(month)).toString();
        Date = day < 10 ? ("0" + (new Integer(day)).toString()) : (new Integer(day)).toString();
        Hour = hour < 10 ? ("0" + (new Integer(hour)).toString()) : (new Integer(hour)).toString();
        Minute = minute < 10 ? ("0" + (new Integer(minute)).toString()) : (new Integer(minute)).toString();
        setDateTime = year + "-" + Month + "-" + Date + " " + Hour + ":" + Minute;
        textTime.setText(setDateTime);
    }

    private void showVoiceDate(int year, int month, int day, int hour, int minute) {
        String Month;
        String Date;
        String Hour;
        String Minute;
        Month = month < 10 ? ("0" + (new Integer(month)).toString()) : (new Integer(month)).toString();
        Date = day < 10 ? ("0" + (new Integer(day)).toString()) : (new Integer(day)).toString();
        Hour = hour < 10 ? ("0" + (new Integer(hour)).toString()) : (new Integer(hour)).toString();
        Minute = minute < 10 ? ("0" + (new Integer(minute)).toString()) : (new Integer(minute)).toString();
        setDateTime = year + "-" + Month + "-" + Date + " " + Hour + ":" + Minute;
        voiceTime.setText(setDateTime);
    }

    private void saveTodoText() {
        String contentValue = textContent.getText().toString();
        if (contentValue.trim().equalsIgnoreCase("")) {
            Toast.makeText(self.getBaseContext(), "请填写备忘的内容", Toast.LENGTH_SHORT).show();
            return;
        }
        if (contentValue.replaceAll("[^\\x00-\\xff]", "**").length() / 2 > 100) {
            Toast.makeText(self.getBaseContext(), "内容超出长度", Toast.LENGTH_SHORT).show();
            return;
        }
        if (DateTimeUtil.timeIsPast(setDateTime)) {
            Toast.makeText(self.getBaseContext(), "设定的时间已过期", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            JSONObject todoItem = new JSONObject();
            todoItem.put("type", "text");
            todoItem.put("create_time", DateTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm"));
            todoItem.put("due_time", setDateTime);
            todoItem.put("content", contentValue);
            if (TodoModel.add(todoItem)) {
                Toast.makeText(self.getBaseContext(), "保存成功", Toast.LENGTH_SHORT).show();
                textWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_out);
                textWindow.startAnimation(animation);
                textWindow.setVisibility(View.GONE);
                textContent.setText("");
                loadTodoList();
            } else {
                Toast.makeText(self.getBaseContext(), "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(self.getBaseContext(), "保存失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveTodoVoice() {
        if (voiceLengthRecorded <= 0) {
            Toast.makeText(self.getBaseContext(), "录音长度过短，请重试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (DateTimeUtil.timeIsPast(setDateTime)) {
            Toast.makeText(self.getBaseContext(), "设定的时间已过期", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            JSONObject todoItem = new JSONObject();
            todoItem.put("type", "voice");
            todoItem.put("create_time", DateTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm"));
            todoItem.put("due_time", setDateTime);
            todoItem.put("content", "[音频文件]");
            todoItem.put("voice_path", currentVoicePath);
            todoItem.put("voice_length", voiceLengthRecorded + "s");
            if (TodoModel.add(todoItem)) {
                Toast.makeText(self.getBaseContext(), "保存成功", Toast.LENGTH_SHORT).show();
                voiceWindow.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.fade_out);
                voiceWindow.startAnimation(animation);
                voiceWindow.setVisibility(View.GONE);
                currentVoicePath = null;
                voiceLengthRecorded = 0;
                voiceLength.setText("可录音：" + voiceLengthMax + "s");
                loadTodoList();
            } else {
                Toast.makeText(self.getBaseContext(), "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(self.getBaseContext(), "保存失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadTodoList() {
        todoListLayout.removeAllViews();
        try {
            JSONArray todoList = TodoModel.retrieveTodoList();
            if (todoList == null || todoList.length() <= 0) {
                return;
            }
            for (int i = 0; i < todoList.length(); i++) {
                final int index = i;
                final JSONObject todoItem = todoList.getJSONObject(i);
                View todoItemView = getLayoutInflater().inflate(R.layout.todo_item, todoListLayout, false);
                TextView todoTime = (TextView) todoItemView.findViewById(R.id.todo_time);
                todoTime.setText("提醒时间：" + todoItem.getString("due_time"));
                Button todoDelete = (Button) todoItemView.findViewById(R.id.todo_delete);
                todoDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TodoModel.remove(index);
                        loadTodoList();
                    }
                });
                if (todoItem.getString("type").equalsIgnoreCase("text")) {
                    TextView todoContent = (TextView) todoItemView.findViewById(R.id.todo_content);
                    todoContent.setText(todoItem.getString("content"));
                    todoContent.setVisibility(View.VISIBLE);
                } else if (todoItem.getString("type").equalsIgnoreCase("voice")) {
                    Button todoPlay = (Button) todoItemView.findViewById(R.id.todo_voice_play);
                    todoPlay.setVisibility(View.VISIBLE);
                    todoPlay.setText("播放音频 [" + todoItem.getString("voice_length") + "] ");
                    todoPlay.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            try {
                                playVoice(todoItem.getString("voice_path"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                todoListLayout.addView(todoItemView, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void voiceRecordMotionEventHandler(MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                press.setVisibility(View.VISIBLE);
                release.setVisibility(View.GONE);
                startRecording();
                break;
            case MotionEvent.ACTION_UP:
                Log.e("Action = ","up");
                press.setVisibility(View.GONE);
                release.setVisibility(View.VISIBLE);
                stopRecording();
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("Action = ","move");
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }
    }

    private void startRecording() {
        if (!voiceIsRecording) {
            voiceRecorder = new MediaRecorder();
            try {
                String fileName = "/" + DateTimeUtil.getCurrentTime("yyyy_MM_dd_HH_mm_ss") + ".3gp";
                String filePath = StorageUtils.audioDir.toString() + fileName;
                File audioPath = new File(StorageUtils.audioDir.toString());
                if (!StorageUtils.fileExists(audioPath.toString())) {
                    audioPath.mkdir();
                }
                if (currentVoicePath != null) {
                    StorageUtils.removeDirectory(new File(currentVoicePath));
                }
                currentVoicePath = filePath;
                voiceRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                voiceRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                voiceRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                voiceRecorder.setOutputFile(filePath);
                voiceRecorder.prepare();
                voiceRecorder.start();
                voiceIsRecording = true;

                voiceLength.setText("可录音：" + voiceLengthMax + "s");
                voiceRecordTimer = new Timer();
                voiceRecordTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        if (voiceLengthMax > 0) {
                            voiceLengthMax--;
                            msg.what = 1;
                        } else {
                            msg.what = 0;
                        }
                        voiceRecordHandler.sendMessage(msg);
                    }
                };
                voiceRecordTimer.schedule(voiceRecordTimerTask, 0, 1000);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(self.getBaseContext(), "录音失败，请检查你的手机", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void stopRecording() {
        if (voiceIsRecording) {
            voiceRecorder.stop();
            voiceRecorder.release();
            voiceRecorder = null;
            voiceIsRecording = false;
            voiceRecordTimer.cancel();
            voiceRecordTimerTask.cancel();
            voiceLengthRecorded = 60 - voiceLengthMax;
            voiceLength.setText("已录音：" + voiceLengthRecorded + "s");
            voiceLengthMax = 60;
        }
    }

    private void playVoice(String path) {
        if (voiceIsPlaying) {
            voicePlayer.release();
            voicePlayer = null;
        }
        voicePlayer = new MediaPlayer();
        try {
            voicePlayer.setDataSource(path);
            voicePlayer.prepare();
            voicePlayer.start();
            voiceIsPlaying = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class EditChangeListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            String content = charSequence.toString();
            content = content.replaceAll("[^\\x00-\\xff]", "**");
            int length = content.length() / 2;
            textHint.setText("可输入 " + (100 - length) + " / 100 字");
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    }
}
